package jsp;

import entity.User;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.*;
import java.util.Random;

/**
 * @author 石小俊
 */
@WebServlet("*.code")
public class CodeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        switch (path) {
            case "/show.code":
                showCode(req, resp);
                break;
            case "/login.code":
                login(req, resp);
                break;
            case "/logout.code":
                logout(req, resp);
                break;
        }
    }

    protected void showCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 在内存中定义一个画板
        BufferedImage image = new BufferedImage(50, 25, BufferedImage.TYPE_INT_RGB);
        // 获取画笔
        Graphics graphics = image.getGraphics();
        // 指定画笔所填充的矩形区域
        graphics.fillRect(0, 0, 50, 25);
        // 设置颜色,此处可以设置一个随机色
        Random random = new Random();
        graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        // 设置字体
        graphics.setFont(new Font("宋体", Font.BOLD + Font.ITALIC, 18));
        // 生成验证码内容,要求随机4位英文字母或者数字
        // 指定一个字符串,该字符串中包含验证码中一切可能出现的字符
        // 获取随机索引位置的字符
        String s = "0123456789qwertyuipolkjhgfdsazxcvbnm";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        String code = buffer.toString();

        // 生成验证码之后,将其数据保存到session,便于校验
        req.getSession().setAttribute("code", code);
        System.out.println("验证码:" + code);

        // 将生成的随机字符串填充到画板中
        graphics.drawString(code, 5, 18);
        // 生成图片
        ImageIO.write(image, "JPEG", resp.getOutputStream());
    }

    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 清除session中的数据
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath()+"/jsp/main2.jsp");
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取表单数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        // 获取图片中的验证码信息
        String image = (String) req.getSession().getAttribute("code");

        // 先比较验证码
        if (!code.equals(image)) {
            req.setAttribute("loginMsg", "验证码不正确");
            req.getRequestDispatcher("/jsp/login2.jsp").forward(req, resp);
            return;
        }
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;
        try {
            // 根据主键查询员工信息
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username = ?")
                    .append(" and password = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                // 在执行用户登录操作的时候,如果登录成功,则将当前用户信息保存到session中
                req.getSession().setAttribute("user",user);
                // 在执行登录操作之后,一般使用重定向跳转到主页
                resp.sendRedirect(req.getContextPath()+"/jsp/main2.jsp");
                return;
            }
            req.setAttribute("loginMsg","用户名或密码错误");
            req.getRequestDispatcher("/jsp/login2.jsp").forward(req,resp);
        } catch (ClassNotFoundException e) {
            req.setAttribute("loginMsg","未找到驱动");
            req.getRequestDispatcher("/jsp/login2.jsp").forward(req,resp);
        } catch (SQLException e) {
            req.setAttribute("loginMsg","数据访问异常");
            req.getRequestDispatcher("/jsp/login2.jsp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("loginMsg","服务器内部异常");
            req.getRequestDispatcher("/jsp/login2.jsp").forward(req,resp);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放连接失败");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放状态集失败");
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放结果集失败");
                }
            }
        }

        // 后进行数据库查询
    }
}
